package com.henan.caigou.service.impl;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

@Service
public class CaptchaService {

    public String recognizeCaptcha(BufferedImage image) {
        try {
            ITesseract instance = new Tesseract();
            instance.setDatapath("D:\\Tesseract-OCR\\tessdata"); // 设置tessdata路径
            instance.setLanguage("eng"); // 设置语言
            return instance.doOCR(image).trim();
        } catch (TesseractException e) {
            throw new RuntimeException("OCR识别失败", e);
        }
    }

    /**
     * 图像预处理（可根据实际验证码调整）
     */
    public BufferedImage preprocessImage(BufferedImage original) {
        int width = original.getWidth();
        int height = original.getHeight();

        // 创建一个新的 BufferedImage 对象用于存储处理后的图像
        BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);

        // 获取图像的图形上下文
        java.awt.Graphics2D g = result.createGraphics();

        // 将原始图像绘制到新的 BufferedImage 上，并进行灰度化和二值化处理
        g.drawImage(original, 0, 0, null);

        // 释放图形上下文资源
        g.dispose();

        return result;
    }
}